<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Model\FastappArticle;
use App\Fastapp\Model\FastappCategoryArticle;
use App\Fastapp\Model\FastappTagArticle;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 文章列表Mapper类
 */
class FastappArticleMapper extends AbstractMapper
{
    /**
     * @var FastappArticle
     */
    public $model;

    public function assignModel()
    {
        $this->model = FastappArticle::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        // 显示
        if (isset($params['status']) && filled($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        // 调用代码
        if (isset($params['code']) && filled($params['code'])) {
            $query->where('code', '=', $params['code']);
        }

        if (isset($params['account_type']) && filled($params['account_type'])) {
            if (!is_array($params['account_type'])) $params['account_type'] = [$params['account_type']];
            $query->whereIn('account_type', $params['account_type']);
        }
        return $query->with(['categoryArticle'])->orderByDesc('id');
    }

    public function save(array $data): mixed
    {
        $id = parent::save($data);
        if ($id && !empty($data['category_id'])) $this->ins($data['category_id'], $id);
        if ($id && !empty($data['tag_id'])) $this->ins($data['tag_id'], $id, 'tag_id');
        return $id;
    }

    public function update(mixed $id, array $data): bool
    {
        $s = parent::update($id, $data);
        FastappCategoryArticle::query()->where(['article_id' => $id])->delete();
        FastappTagArticle::query()->where(['article_id' => $id])->delete();
        if (!empty($data['category_id'])) $this->ins($data['category_id'], $id);
        if (!empty($data['tag_id'])) $this->ins($data['tag_id'], $id, 'tag_id');
        return $s;
    }

    public function ins(array $category_id, $id, string $field = 'category_id'): void
    {
        $in = [];
        foreach ($category_id as $cate_id) {
            $in[] = [
                $field => $cate_id,
                'article_id' => $id
            ];
        }
        if ($in && $field == 'category_id') FastappCategoryArticle::query()->insert($in);
        if ($in && $field == 'tag_id') FastappTagArticle::query()->insert($in);
    }

    public function handlePageItems(array $items, array $params): array
    {
        foreach ($items as $item) {
            $item->setHidden(['categoryArticle', 'categoryTag']);
            $item->category_id = array_column($item->categoryArticle->toArray(), 'category_id');
            $item->tag_id = array_column($item->categoryTag->toArray(), 'tag_id');
        }
        return $items;
    }
}